package com.wdh.kjs.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lidong.photopicker.PhotoPickerActivity;
import com.lidong.photopicker.PhotoPreviewActivity;
import com.lidong.photopicker.SelectModel;
import com.lidong.photopicker.intent.PhotoPickerIntent;
import com.lidong.photopicker.intent.PhotoPreviewIntent;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.MyCookieStore;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.model.Picture;
import com.wdh.kjs.model.PictureModel;
import com.wdh.kjs.util.DeleteFileUtil;
import com.wdh.kjs.util.ImageFactory;
import com.wdh.kjs.util.ToastUtils;
import com.wdh.kjs.widget.MyGridView;

import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by feifei on 2016/8/11.
 */
public class LawProveActivity extends BaseTopActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    private MyGridView gv_select_house_picture;
    private String imgs = "000000";
    private int clickPosition = 0;
    private ArrayList<String> imagePaths = new ArrayList<>();
    private static final int MY_PERMISSIONS_REQUEST_STORAGE_CODE = 17;
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;
    private static final int REQUEST_PREVIEW_CODE_BEFORE = 50;
    private GridAdapter gridAdapter;
    private MyGridView gv_select_house_picture_before;
    private SharedPreferences sharedPreferencesjichu;
    private String jsonString;
    private List<String> listString = new ArrayList<>();
    private MyGridAdapter mygridAdapter;
    private List<String> compressImageList = new ArrayList<>();
    //    private List<String> compressHouseTypeImageList = new ArrayList<>();  //图片压缩
    private ArrayList<String> listExtra = new ArrayList<>();
    private Button upload;
    private Picture picture;
    private TextView tv_publish_title;
    private File newFile = null;
    private final static int ESF_HOUSE_TYPE = 0;
    private HashMap<String, File> selectImageFileMap = new HashMap<>();
    private JsonModel jsonModel;
    private PictureModel pictureModel;
    private int totalImageNum = 0;
    private String partyId;
    private String zhanghu;
    private String mima;
    private List<String> houseTypePathList = new ArrayList<>(); //图片路径
    private List<String> idList = new ArrayList<>();
    private Intent intent;
    private String lawId;
    private List<String> MyIdList = new ArrayList<>();
    private Map<String, String> IdAndFile = new HashMap<>();//key:上传的文件Id，Value：上传的文件名
   ProgressDialog m_pDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pushpicture);
        initTopBar("相关法律材料");
        SharedPreferences sharedPreferences = getSharedPreferences("logininfo", MODE_PRIVATE);
        partyId = sharedPreferences.getString("loginToken", "");
        zhanghu = sharedPreferences.getString("zhanghao", "");
        mima = sharedPreferences.getString("mima", "");

        m_pDialog = new ProgressDialog(LawProveActivity.this);
        m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        m_pDialog.setIcon(R.drawable.logo);
        m_pDialog.setTitle("温馨提示");
        m_pDialog.setMessage("不要着急，图片正在上传中哦~~~");
        m_pDialog.setCancelable(true);

        denglu();
        upload = (Button) findViewById(R.id.upload);
        tv_publish_title = (TextView) findViewById(R.id.tv_publish_title);
        tv_publish_title.setText("(请提供相关法律材料，包括但不限于：借款协议、评估报告、仓单凭证、仓储合同、24小时质押物实时监控、购销合同、担保合同、保险合同)");

        gv_select_house_picture = (MyGridView) findViewById(R.id.gv_select_house_picture);
        gv_select_house_picture_before = (MyGridView) findViewById(R.id.gv_select_house_picture_before);
        gv_select_house_picture_before.setOnItemClickListener(new AdapterViewOnItemClickListener());

        sharedPreferencesjichu = getSharedPreferences("zhaopian", MODE_PRIVATE);
        jsonString = sharedPreferencesjichu.getString("law", "");
        lawId = sharedPreferencesjichu.getString("lawId", "");

        if (!jsonString.equals("")) {
            listString = JSON.parseArray(jsonString, String.class);
            mygridAdapter = new MyGridAdapter((ArrayList<String>) listString);
            gv_select_house_picture_before.setAdapter(mygridAdapter);
        }
        imagePaths.add("000000");
        gridAdapter = new GridAdapter(imagePaths);
        gv_select_house_picture.setOnItemClickListener(this);
        gv_select_house_picture.setAdapter(gridAdapter);
        upload.setOnClickListener(this);
    }

    private void denglu() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("USERNAME", zhanghu);
        params.addBodyParameter("PASSWORD", mima);
        final HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_LOGIN, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                String m = jsonModel.getPartyId();
                if (jsonModel._LOGIN_PASSED_()) {
                    DefaultHttpClient zpf = (DefaultHttpClient) http.getHttpClient();
                    MyCookieStore.firstCookieStore = zpf.getCookieStore();
                    SharedPreferences.Editor editor = getSharedPreferences("logininfo", MODE_PRIVATE).edit();
                    editor.putString("loginToken", jsonModel.getPartyId());
                    editor.putString("nickName", jsonModel.getNickName());
                    editor.putString("phoneNumber", jsonModel.getPhoneNumber());
                    editor.putString("levels", jsonModel.getLevels());
                    editor.putString("type", jsonModel.getType());
                    editor.putString("zhanghao", zhanghu);
                    editor.putString("mima", mima);
                    editor.commit();
                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }
        });

    }

    private void LoadFolderAndImages() {
        if ("000000".equals(imgs)) {
            PhotoPickerIntent intent = new PhotoPickerIntent(LawProveActivity.this);
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true); // 是否显示拍照
            intent.setMaxTotal(6); // 最多选择照片数量，默认为6
            intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
            startActivityForResult(intent, REQUEST_CAMERA_CODE);
        } else {
            PhotoPreviewIntent intent = new PhotoPreviewIntent(LawProveActivity.this);
            intent.setCurrentItem(clickPosition);
            intent.setPhotoPaths(imagePaths);
            startActivityForResult(intent, REQUEST_PREVIEW_CODE);
        }
    }

    public void requestReadStorageRuntimePermission() {
        if (ContextCompat.checkSelfPermission(LawProveActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(LawProveActivity.this,
//                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
//                    MY_PERMISSIONS_REQUEST_STORAGE_CODE);
        } else {
            LoadFolderAndImages();
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        imgs = (String) parent.getItemAtPosition(position);
        clickPosition = position;
        requestReadStorageRuntimePermission();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.upload:
                m_pDialog.show();
                releaseHouseSource();
        }
    }

    private void releaseHouseSource() {


        selectImageFileMap.clear();
        if (compressImageList.size() > 0) {
            if (compressImageList.contains("000000")) {
                compressImageList.remove("000000");
            }
            upload.setClickable(false);
            new ImageCompressTask().execute();
        }

    }

    /**
     * 图片压缩
     */
    private class ImageCompressTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//            showDialog();
        }

        @Override
        protected Void doInBackground(Void... params) {

            for (int i = 0; i < compressImageList.size(); i++) {
                File oldFile = new File(compressImageList.get(i));
                String newFilePath = compressImageList.get(i);

                try {
                    ImageFactory.compressAndGenImage(compressImageList.get(i), newFilePath, 1024, false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                newFile = new File(newFilePath);

                selectImageFileMap.put(compressImageList.get(i), newFile);
            }


            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            Log.e("imagePathMap", "imagePathMap" + selectImageFileMap.toString());
            houseTypePathList.clear();

            totalImageNum = selectImageFileMap.size();
            if (totalImageNum > 0) {
                if (!lawId.equals("")) {
                    MyIdList = JSON.parseArray(lawId, String.class);
                } else {
                    MyIdList = new ArrayList<>();
                }
                for (int i = 0; i < compressImageList.size(); i++) {
                    if (selectImageFileMap.containsKey(compressImageList.get(i))) {
                        newFile = selectImageFileMap.get(compressImageList.get(i));
                        uploadFile(newFile, ESF_HOUSE_TYPE, compressImageList.get(i));
                    }
                }

            }


        }
    }

    private void uploadFile(File newFile, int esfHouseType, final String m) {
        if (esfHouseType == ESF_HOUSE_TYPE) {     //上传户型

            RequestParams params = new RequestParams();
            params.addBodyParameter("uploadedFile", newFile);
            params.addBodyParameter("filePathOrName", m);
            params.addBodyParameter("documentType", "7");
//                //暂时没加上地址、上传文件
//                params.addBodyParameter("fileInfoList", JSON.toJSONString(picture));
            HttpUtils http = new HttpUtils();
            http.configCookieStore(MyCookieStore.firstCookieStore);
            http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_PICTURE, params, new RequestCallBack<String>() {

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {


                    Gson gson = new Gson();
                    pictureModel = gson.fromJson(responseInfo.result, PictureModel.class);


                    if (pictureModel.isSuccess()) {
                        m_pDialog.dismiss();
                        idList.add(pictureModel.getResult());
                        IdAndFile.put(pictureModel.getResult(), m);
                        totalImageNum--;
                        Toast.makeText(LawProveActivity.this, pictureModel.getMsg(), Toast.LENGTH_SHORT).show();
                        if (totalImageNum == 0) {
                            for (int i = 0; i < idList.size(); i++) {
                                String id = idList.get(i);
                                MyIdList.add(id);
                                listString.add(IdAndFile.get(id));
                            }
                            SharedPreferences.Editor editor = getSharedPreferences("zhaopian", MODE_PRIVATE).edit();
                            editor.putString("lawId", JSON.toJSONString(MyIdList));
                            editor.putString("law", JSON.toJSONString(listString));
                            editor.putString("lawsize", listString.size() + "");
                            editor.commit();
                            intent = new Intent();
                            intent.setClass(LawProveActivity.this, UploadProjectInfoActivity.class);
                            intent.putStringArrayListExtra("law", (ArrayList<String>) MyIdList);
                            setResult(7, intent);
                            finish();
                        }
                    } else
//                            ToastUtils.showShort(getActivity(), jsonModel.getMes());
                        Toast.makeText(LawProveActivity.this, pictureModel.getMsg(), Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onFailure(HttpException error, String msg) {
                    Log.i("gggggg", error.getExceptionCode() + msg + "");
                    ToastUtils.showShort(LawProveActivity.this, "网络异常！");
                }
            });


        }
    }

    private class MyGridAdapter extends BaseAdapter {

        private ArrayList<String> listUrls;
        private LayoutInflater inflater;

        public MyGridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if (listUrls.size() == 10) {
                listUrls.remove(listUrls.size() - 1);
            }
            inflater = LayoutInflater.from(LawProveActivity.this);
        }

        public int getCount() {
            return listUrls.size();
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.i_item_select_image, parent, false);
                holder.image = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final String path = listUrls.get(position);
            if (path.equals("000000")) {
                holder.image.setImageResource(R.drawable.financing_didn_t);
                holder.image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        List<String> mylist = new ArrayList<>();
//                        mylist.add("000000");
                        SharedPreferences.Editor editor = getSharedPreferences("zhaopian", MODE_PRIVATE).edit();
                        editor.putString("law", JSON.toJSONString(mylist));
                        editor.putString("lawsize", "0");
                        editor.commit();
                        gv_select_house_picture_before.setVisibility(View.GONE);
                    }
                });
            } else {
                Glide.with(LawProveActivity.this)
                        .load(path)
                        .error(R.mipmap.ic_launcher)
                        .centerCrop()
                        .crossFade()
                        .into(holder.image);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView image;
        }
    }

    private class GridAdapter extends BaseAdapter {

        private ArrayList<String> listUrls;
        private LayoutInflater inflater;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if (listUrls.size() == 7) {
                listUrls.remove(listUrls.size() - 1);
            }
            inflater = LayoutInflater.from(LawProveActivity.this);
        }

        public int getCount() {
            return listUrls.size();
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.i_item_select_image, parent, false);
                holder.image = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final String path = listUrls.get(position);
            if (path.equals("000000")) {
                holder.image.setImageResource(R.drawable.upload);
            } else {
                Glide.with(LawProveActivity.this)
                        .load(path)
                        .error(R.mipmap.ic_launcher)
                        .centerCrop()
                        .crossFade()
                        .into(holder.image);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView image;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE: {
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    Log.d("list", "list: " + "list = [" + list.size());
                    loadAdpater(list);
                    compressImageList.clear();
                    compressImageList.addAll(list);
                   /* for(int i=0;i<compressImageList.size();i++){

                        listString.add(compressImageList.get(i));
                    }
                    if (listString.size()!=0) {
                        listString.remove(listString.size() - 1);
                    }

                    String m = JSON.toJSONString(compressImageList);
                    SharedPreferences.Editor editor = getSharedPreferences("zhaopian", MODE_PRIVATE).edit();
                    editor.putString("law", JSON.toJSONString(listString));
                    editor.putString("lawsize",listString.size()+"");
                    editor.commit();*/
                    break;
                }
                // 预览
                case REQUEST_PREVIEW_CODE: {
                    listExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    ArrayList<String> delete_path = data.getStringArrayListExtra(PhotoPreviewActivity.DELETE_PATH);
                    loadAdpater(listExtra);
                    compressImageList.removeAll(delete_path);
                    break;
                }
                case REQUEST_PREVIEW_CODE_BEFORE: {//删除已经上传的文件
                    delete_file_before(data);
                    break;
                }
                default: {
                    break;
                }
            }
        }
    }

    private void loadAdpater(ArrayList<String> paths) {
        if (imagePaths != null && imagePaths.size() > 0) {
            imagePaths.clear();
        }
        if (paths.contains("000000")) {
            paths.remove("000000");
        }
        paths.add("000000");
        imagePaths.addAll(paths);
        gridAdapter = new GridAdapter(imagePaths);
        gv_select_house_picture.setAdapter(gridAdapter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_STORAGE_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    LoadFolderAndImages();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(LawProveActivity.this, "权限错误，无法正常工作！", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }


    /**
     * 删除已经上传的文件
     *
     * @param data
     */
    private void delete_file_before(Intent data) {
        listExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
        ArrayList<String> delete_path_before = data.getStringArrayListExtra(PhotoPreviewActivity.DELETE_PATH);
        ArrayList<String> deletId = DeleteFileUtil.getDeletId(listString, delete_path_before, lawId);
        listString = DeleteFileUtil.getRemainFile(listString, delete_path_before);

        MyIdList = DeleteFileUtil.getRemainId(lawId, deletId);
        lawId = JSON.toJSONString(MyIdList);

        DeleteFileUtil.DeletRongziFile(deletId);

        mygridAdapter = new MyGridAdapter((ArrayList<String>) listString);
        gv_select_house_picture_before.setAdapter(mygridAdapter);
        SharedPreferences.Editor editor = getSharedPreferences("zhaopian", MODE_PRIVATE).edit();
        editor.putString("law", JSON.toJSONString(listString));
        editor.putString("lawsize", listString.size() + "");
        editor.putString("lawId", lawId);
        editor.commit();
    }

    class AdapterViewOnItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            imgs = (String) parent.getItemAtPosition(position);
            clickPosition = position;
            if (ContextCompat.checkSelfPermission(LawProveActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(LawProveActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_STORAGE_CODE);
            }
            PhotoPreviewIntent intent = new PhotoPreviewIntent(LawProveActivity.this);
            intent.setCurrentItem(clickPosition);
            intent.setPhotoPaths((ArrayList<String>) listString);
            startActivityForResult(intent, REQUEST_PREVIEW_CODE_BEFORE);
        }
    }
}
